#-*-coding:utf-8-*-
import sys, os, time, zipfile
from PyQt4 import QtCore, QtGui
from liburl import Download
from noplatform import *
from fonk import VERSION, byte, html_yaz, dogrulama, mesaj, listele, dizin_sil
from urllib import urlopen, urlretrieve

arguman = sys.argv

if not os.path.isdir("packages"):
    try:
        os.mkdir("packages")
    except:
        pass

class Islem(QtGui.QDialog):
    def __init__(self, ui):
        QtGui.QDialog.__init__(self)
        self.ui = ui
        self.resize(300,85)
        self.setWindowIcon(QtGui.QIcon(os.path.join("resim",u"parçala.png")))
        self.setWindowFlags(QtCore.Qt.SplashScreen)
        self.parca_adi = QtGui.QLabel(self)
        self.parca_adi.setGeometry(5,5,290,20)
        self.parca_adi2 = QtGui.QLabel(self)
        self.parca_adi2.setGeometry(5,30,290,20)
        self.progres = QtGui.QProgressBar(self)
        self.progres.setGeometry(5,55,290,25)
        self.progres.setProperty("value", 0)

        self.timer = QtCore.QBasicTimer()
        self.say = 0
        self.onStart()
        self.connect(self, QtCore.SIGNAL("say(int)"), self.progres.setValue)

    def timerEvent(self, event):
        self.o = open(self.ui.lineNerden.text(), "rb")
        oku = 1024*1024
        boyut = int(os.path.getsize(self.ui.lineNerden.text()))/oku+1
        self.progres.setMaximum(boyut)

    def onStart(self):
        self.timer.start(10, self)
    
    def keyPressEvent(self, event):
        pass



class PDZ(QtCore.QThread):
    def __init__(self, ui, depo):
        QtCore.QThread.__init__(self)
        self.ui = ui
        self.depo = depo
        self.zipfile = zipfile.ZipFile("Setup.pdz","w",8)

    def run(self):
        liste = listele("packages")
        say = 0
        for i in liste:
            say += 1
            self.ui.dosya_ismi.setText(i)
            self.zipfile.write(i)
            app.processEvents()
            self.ui.progressBar.setMaximum(len(liste))
            self.emit(QtCore.SIGNAL("say(int)"), say)

        if self.depo == None:
            pass
        else:
            for i in self.depo:
                self.ui.dosya_ismi.setText("%s deposu indiriliyor..."%i[0])
                index = urlretrieve("%s"%i[-1], "%s-pisi-index.xml.bz2"%i[0])
                time.sleep(2)
                self.ui.dosya_ismi.setText("%s deposu ekleniyor..."%i[0])
                self.zipfile.write("%s-pisi-index.xml.bz2"%i[0])
                time.sleep(2)
                self.ui.dosya_ismi.setText("%s deposu eklendi."%i[0])
                os.remove("%s-pisi-index.xml.bz2"%i[0])
                time.sleep(2)
        self.zipfile.close()

class Setup(QtGui.QDialog):
    def __init__(self, depo):
        QtGui.QDialog.__init__(self)
        self.depo = depo
        self.resize(250, 80)
        self.gridLayout = QtGui.QGridLayout(self)
        self.arsiv_adi = QtGui.QLabel(self)
        self.gridLayout.addWidget(self.arsiv_adi, 0, 0, 1, 1)
        self.dosya_ismi = QtGui.QLabel(self)
        self.gridLayout.addWidget(self.dosya_ismi, 1, 0, 1, 1)
        self.progressBar = QtGui.QProgressBar(self)
        self.progressBar.setProperty("value", 0)
        self.gridLayout.addWidget(self.progressBar, 2, 0, 1, 1)

        self.setWindowFlags(QtCore.Qt.SplashScreen)
        self.setWindowTitle("")
        self.arsiv_adi.setText(u"Setup.pdz")
        self.dosya_ismi.setText(u"")
        self.progressBar.setFormat("%%p")

        self.pdz = PDZ(self, self.depo)
        self.pdz.start()
        
        QtCore.QObject.connect(self.pdz, QtCore.SIGNAL("finished()"), self.close)
        QtCore.QObject.connect(self.pdz, QtCore.SIGNAL("say(int)"), self.progressBar.setValue)
        
    def keyPressEvent(self, event):
        pass

class Options(QtGui.QDialog):
    def __init__(self, ui):
        QtGui.QDialog.__init__(self)
        self.ui = ui
        self.resize(250, 155)
        self.setMinimumSize(250,255)
        self.setWindowIcon(QtGui.QIcon(os.path.join("images", "odun.png")))
        self.gridLayout = QtGui.QGridLayout(self)
        self.groupBox = QtGui.QGroupBox(self)
        self.groupBox.setCheckable(True)
        self.gridLayout2 = QtGui.QGridLayout(self.groupBox)
        self.gridLayout.addWidget(self.groupBox, 0, 0, 1, 1)
        self.buttonBox = QtGui.QDialogButtonBox(self)
        self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
        self.gridLayout.addWidget(self.buttonBox, 1, 0, 1, 1)
		
        self.listWidget = QtGui.QListWidget(self)
        self.gridLayout2.addWidget(self.listWidget, 0, 0, 1, 1)
        self.listWidget.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
        
        self.setWindowTitle(u"Seçenekler")
        self.groupBox.setTitle(u"Depo İndexlerini Yenile")
        
        self.listele()
        
        QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("accepted()"), self.secenek_al)
        QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("rejected()"), self.close)

    def listele(self):
        if str(self.ui.xmlfile)[-3:] == "xml":
            self.depolist = getReposFromInstalledXml(self.ui.xmlfile)
            print "xml",self.ui.xmlfile
        else:
            self.depolist = getReposFromPDX(self.ui.xmlfile)
            print "pdx",self.ui.xmlfile, self.depolist
        sira = 0
        for depo in self.depolist:
            QtGui.QListWidgetItem(self.listWidget)
            self.listWidget.item(sira).setText(depo[0])
            sira += 1

    def keyPressEvent(self, event):
        pass

    def secenek_al(self):
	depolist = self.listWidget.selectedItems()
	for i in depolist:
	    print i.text()
        if self.groupBox.isChecked():
            if len(self.listWidget.selectedItems()) == 0:
                uyar = QtGui.QMessageBox.warning(self, u"Uyarı",
                                                  u"Depo seçmezseniz indexler yoksayılacak!",
                                                  QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)

                if uyar == QtGui.QMessageBox.Yes:
                    self.close()
                    pdz = Setup(None)
                    pdz.exec_()

            if len(depolist) > 0:
                l = []
                for depo in depolist:
                    for ad, url in self.depolist:
                        print depo.text(), ad, url
                        if depo.text() == ad:
                            l.append((ad,url))
                print l
                self.close()
                pdz = Setup(l)
                pdz.exec_()
        else:
            self.close()
            pdz = Setup(None)
            pdz.exec_()

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.resize(400, 150)
        self.setMinimumSize(400, 150)
        self.setMaximumSize(400, 150)
        self.setWindowIcon(QtGui.QIcon(os.path.join("images", "odun.png")))
        self.cw = QtGui.QWidget(self)
        self.gridLayout = QtGui.QGridLayout(self.cw)
        self.konum = QtGui.QLabel(self.cw)
        self.gridLayout.addWidget(self.konum, 0, 0, 1, 1)
        self.url = QtGui.QLabel(self.cw)
        self.gridLayout.addWidget(self.url, 0, 1, 1, 4)
        self.pisi_label = QtGui.QLabel(self.cw)
        self.gridLayout.addWidget(self.pisi_label, 1, 0, 1, 1)
        self.paket = QtGui.QLabel(self.cw)
        self.gridLayout.addWidget(self.paket, 1, 1, 1, 4)
        self.progressBar = QtGui.QProgressBar(self.cw)
        self.progressBar.setProperty("value", 0)
        self.gridLayout.addWidget(self.progressBar, 2, 0, 1, 8)
        self.indir = QtGui.QPushButton(self.cw)
        self.indir.setEnabled(False)
        self.gridLayout.addWidget(self.indir, 3, 0, 1, 2)
        self.pisixmlac = QtGui.QPushButton(self.cw)
        self.gridLayout.addWidget(self.pisixmlac, 3, 2, 1, 2)
        self.iptal = QtGui.QPushButton(self.cw)
        self.iptal.setEnabled(False)
        self.gridLayout.addWidget(self.iptal, 3, 4, 1, 2)
        self.kapat = QtGui.QPushButton(self.cw)
        self.gridLayout.addWidget(self.kapat, 3, 6, 1, 2)
        self.Boyut = QtGui.QLabel(self.cw)
        self.gridLayout.addWidget(self.Boyut, 1, 5, 1, 1)
        self.boyut = QtGui.QLabel(self.cw)
        self.gridLayout.addWidget(self.boyut, 1, 6, 1, 2)
        self.kalansure = QtGui.QLabel(self.cw)
        self.gridLayout.addWidget(self.kalansure, 0, 5, 1, 1)
        self.sure = QtGui.QLabel(self.cw)
        self.gridLayout.addWidget(self.sure, 0, 6, 1, 2)
        self.durum = QtGui.QLabel(self.cw)
        self.gridLayout.addWidget(self.durum, 4, 0, 1, 8)
        self.setCentralWidget(self.cw)
        self.menubar = QtGui.QMenuBar(self)
        self.mDosya = QtGui.QMenu(self.menubar)
        self.mYardim = QtGui.QMenu(self.menubar)
        self.mDuzenle = QtGui.QMenu(self.menubar)
        self.setMenuBar(self.menubar)
        self.aKapat = QtGui.QAction(self)
        self.aKullanimKlavuzu = QtGui.QAction(self)
        self.aHakkinda = QtGui.QAction(self)
        self.aQtHakkinda = QtGui.QAction(self)
        self.aPDZOlustur = QtGui.QAction(self)
        #self.aPDZOlustur.setEnabled(False)
        self.mDosya.addAction(self.aKapat)
        self.mYardim.addAction(self.aKullanimKlavuzu)
        self.mYardim.addSeparator()
        self.mYardim.addAction(self.aHakkinda)
        self.mYardim.addAction(self.aQtHakkinda)
        self.mDuzenle.addAction(self.aPDZOlustur)
        self.menubar.addAction(self.mDosya.menuAction())
        self.menubar.addAction(self.mDuzenle.menuAction())
        self.menubar.addAction(self.mYardim.menuAction())

        self.retranslateUi()
        QtCore.QObject.connect(self.aHakkinda, QtCore.SIGNAL("triggered(bool)"), self.hakkinda)
        QtCore.QObject.connect(self.aKapat, QtCore.SIGNAL("triggered(bool)"), self.close)
        QtCore.QObject.connect(self.aKullanimKlavuzu, QtCore.SIGNAL("triggered(bool)"), self.klavuz)
        QtCore.QObject.connect(self.aQtHakkinda, QtCore.SIGNAL("triggered(bool)"), QtGui.QApplication.aboutQt)
        QtCore.QObject.connect(self.aPDZOlustur, QtCore.SIGNAL("triggered(bool)"), self.PDZolustur)
        QtCore.QObject.connect(self.kapat, QtCore.SIGNAL("clicked(bool)"), self.close)
        QtCore.QObject.connect(self.pisixmlac, QtCore.SIGNAL("clicked(bool)"), self.xmlac)
        QtCore.QObject.connect(self.indir, QtCore.SIGNAL("clicked(bool)"), self.indirpisi)
        QtCore.QObject.connect(self.iptal, QtCore.SIGNAL("clicked(bool)"), self.iptalet)

        try:
            if os.path.isfile(arguman[1]):
                self.xmlfile = arguman[1]
                self.pisixmlac.setEnabled(False)
                #self.iptal.setEnabled(True)
                self.indir.setEnabled(True)
                yol, xmlname = os.path.split(self.xmlfile)
                self.setWindowTitle(u"Odun Downloader - "+xmlname)
            else:
                sys.exit()
        except IndexError:
            pass

        self.hatalipaketler = []

    def hakkinda(self):
        mesajk = QtGui.QMessageBox.about(self.cw, u"Odun Hakkında", mesaj)

    def klavuz(self):
        pass

    def PDZolustur(self):
        pdz = Options(self)
        pdz.exec_()

    def iptalet(self):
        self.indir.setEnabled(True)
        self.progressBar.setValue("")
        #self.iptal.setEnabled(False)
        self.kapat.setEnabled(True)
        self.aKapat.setEnabled(True)
        self.indir.setEnabled(False)
        self.pisixmlac.setEnabled(True)

    def progress_bar(self, okunan, toplam):
        self.progressBar.setMaximum(toplam)
        self.progressBar.setValue(okunan)
        self.boyut.setText(byte(toplam))
        self.elapsed_time(okunan, toplam, time.time() - self.baslangic)

    def elapsed_time(self, okunan, toplam, zaman):
        kalan  = ((toplam * (zaman / okunan)) - zaman)
        saat   = kalan / 3600
        dakika = (kalan % 3600) / 60
        saniye = kalan % 60
        self.sure.setText("%.2d:%.2d:%.2d" % (saat, dakika, saniye))

    def indirpisi(self):
        #self.iptal.setEnabled(True)
        #self.kapat.setEnabled(False)
        #self.aKapat.setEnabled(False)
        dizin_sil("packages")
        self.indir.setEnabled(False)
        self.pisixmlac.setEnabled(False)
        self.count = 0

        self.pdx = readPDX(self.xmlfile)
        self.paketlistesi = [x for x in self.pdx]
        print self.paketlistesi
        lenPDX = len(self.pdx)
        self.bilgi = []
        self.hatalipaketler = []
        self.detay = open("detay.txt","a")
        self.__indir(True)

    def __indir(self, status):
        self.paket_sayisi = len(self.pdx)-1
        if len(self.pdx) != 0:
            self.pisi = self.pdx.pop()
            self.count += 1
            parcala = self.pisi["url"].split("/")
            self.pisiname = parcala[-1]
            pisiurl = parcala[2]
            self.baslangic = time.time()
            self.pisiindir = Download(self.pisi["url"])
            self.url.setText(self.pisi["url"])
            self.downloadInfo = "%s - %s/%s"%(self.pisi["name"], self.count, self.count+self.paket_sayisi)
            self.paket.setText(self.downloadInfo)

            QtCore.QObject.connect(self.pisiindir, QtCore.SIGNAL("done(bool)"), self.__indir)
            QtCore.QObject.connect(self.pisiindir, QtCore.SIGNAL("dataReadProgress(int,int)"), self.progress_bar)
        else:
            print "Bitti"
            self.aPDZOlustur.setEnabled(True)
            self.indir.setEnabled(False)
            self.pisixmlac.setEnabled(True)
            #self.check()    işlem bitince doğrulama başlar

    def check(self):
        self.durum.setText(u"Kontrol ediliyor...")
        time.sleep(2)
        print self.pisiname
        dogrumu = dogrulama(self.pisiname, self.pisi["hash"])
        print dogrumu
        if dogrumu == True:
            self.durum.setText(u"Başarılı indirme!")
            self.detay.write(self.pisi["name"]+" paketi başarıyla indirildi!\n")
            time.sleep(2)
        else:
            self.durum.setText(u"Hatalı indirme!")
            self.hatalipaketler.append(self.pisi)
            self.detay.write(self.pisi["name"]+" paketi hatalı olarak indirildi! Paket silindi...\n")
            os.remove(os.path.join(os.getcwd(), "packages", self.pisiname))
            time.sleep(2)
            self.bilgi.append((self.pisi["name"],self.pisi["url"]))

    def uyari(self):
        htmlyaz = html_yaz(self.bilgi)
        mesaj = u"""%d hatalı paket yazılımın kurulduğu
        dizinde "hatalipaketler.html" olarak kaydedildi.
        html dosyasından tarayıcınızla indirebilirsiniz.""" % say
        uyar = QtGui.QMessageBox()
        uyar.setWindowTitle(u"Uyarı!")
        uyar.setText(mesaj)
        uyar.exec_()

    def xmlac(self):
        self.xmlfile = QtGui.QFileDialog.getOpenFileName(self,
                                                         u"Odun Dosyası",
                                                         QtCore.QDir.homePath(),
                                                         u"Odun dosyası(*.pdx);; Yüklenmiş Pisi Listesi (*.xml)")
        if os.path.isfile(self.xmlfile) == True:
            if self.xmlfile[-3:] == "xml":
                mesaj = u"""
                XML-PDX Dönüşümü sistemizi biraz etkiler!
                Devam Etmek İstiyor musunuz?
                """
                reply = QtGui.QMessageBox.warning(self,
                                                   u"Uyarı!",
                                                   mesaj,
                                                   QtGui.QMessageBox.Yes,
                                                   QtGui.QMessageBox.No)
                if reply == QtGui.QMessageBox.Yes:
                    # FIXME: thread kullan
                    writeUpdatedPackages(self.xmlfile, "latest_update.pdx")
                    self.xmlfile = "latest_update.pdx"
                    self.xmlac2()
                else:
                    pass
            else:
                self.xmlac2()
        else:
            uyar = QtGui.QMessageBox()
            uyar.setWindowTitle(u"Uyarı")
            uyar.setText(u"Dosya seçmediniz!")
            uyar.exec_()
            self.indir.setEnabled(False)
            #self.iptal.setEnabled(False)
            self.setWindowTitle("Odun Downloader")
        
    def xmlac2(self):
        self.indir.setEnabled(True)
        #self.iptal.setEnabled(True)
        xmlname = self.xmlfile.split("/")
        self.setWindowTitle("Odun Downloader - " + xmlname[-1])

    def retranslateUi(self):
        self.setWindowTitle(u"Odun Downloader")
        self.konum.setText(u"Konum:")
        self.url.setText(u"")
        self.pisi_label.setText(u"Pisi:")
        self.paket.setText(u"")
        self.progressBar.setFormat("%%p")
        self.indir.setText(u"İndir")
        self.pisixmlac.setText(u"Dosya aç")
        self.iptal.setText(u"İptal")
        self.kapat.setText(u"Kapat")
        self.Boyut.setText(u"Boyut:")
        self.boyut.setText(u"")
        self.kalansure.setText(u"Kalan Süre:")
        self.sure.setText(u"")
        self.durum.setText(u"")
        self.mDosya.setTitle(u"Dosya")
        self.mYardim.setTitle(u"Yardım")
        self.mDuzenle.setTitle(u"Düzenle")
        self.aKapat.setText(u"Kapat")
        self.aKullanimKlavuzu.setText(u"Kullanım Klavuzu")
        self.aHakkinda.setText(u"Odun Hakkında")
        self.aQtHakkinda.setText(u"Qt Hakkında")
        self.aPDZOlustur.setText(u"PDZ Oluştur")

    def closeEvent(self, event):
        reply = QtGui.QMessageBox.question(self, u"Mesaj",
        u"Kapatmak istiyor musunuz?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)

        if reply == QtGui.QMessageBox.Yes:
                event.accept()
        else:
                event.ignore()

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    ui = MainWindow()
    ui.show()
    sys.exit(app.exec_())
